package com.xuhuan.practice.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xuhuan.practice.dto.article.ArticleInfoDTO;
import com.xuhuan.practice.dto.page.PageResult;
import com.xuhuan.practice.mapper.ArticleMapper;
import com.xuhuan.practice.entity.Article;
import com.xuhuan.practice.service.ArticleService;
import com.xuhuan.practice.utils.CurrentUserUtil;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @author: huan.xu
 * @create: 2024/6/11 22:00
 * @description: 文章管理接口实现
 **/
@Service
public class ArticleServiceImpl extends
    ServiceImpl<ArticleMapper, Article> implements ArticleService {

  /**
   * 新增文章
   *
   * @param articleInfoDTO
   */
  @Override
  public void add(ArticleInfoDTO articleInfoDTO) {
    Article article = new Article();
    BeanUtils.copyProperties(articleInfoDTO, article);
    article.setCreateTime(LocalDateTime.now());
    article.setUpdateTime(LocalDateTime.now());
    article.setCreateUser(CurrentUserUtil.getCurrentUserId());
    saveOrUpdate(article);
  }

  /**
   * 根据id查询
   *
   * @param articleId
   * @return
   */
  @Override
  public Article getById(Integer articleId) {
    return baseMapper.selectById(articleId);
  }

  /**
   * 根据Id删除
   *
   * @param articleId
   */
  @Override
  public void deleteById(Integer articleId) {
    baseMapper.deleteById(articleId);
  }

  /**
   * 更新文章
   *
   * @param article
   */
  @Override
  public void update(Article article) {
    article.setUpdateTime(LocalDateTime.now());
    saveOrUpdate(article);
  }

  /**
   * 文章列表分页查询
   *
   * @param pageNum    页数
   * @param pageSize   每页条数
   * @param categoryId 文章分类id
   * @param state      文章状态
   * @return
   */
  @Override
  public PageResult<ArticleInfoDTO> list(Integer pageNum, Integer pageSize, Integer categoryId,
      String state) {
    PageResult<ArticleInfoDTO> pageResult = new PageResult<>();
    PageHelper.startPage(pageNum, pageSize);
    List<Article> articleList = baseMapper.list(CurrentUserUtil.getCurrentUserId()
        , categoryId, state);
    Page<Article> page = (Page<Article>) articleList;

    pageResult.setTotal(page.getTotal());
    List<ArticleInfoDTO> articleInfoDTOS = page.getResult().stream()
        .map(article -> {
          ArticleInfoDTO articleInfoDTO = new ArticleInfoDTO();
          BeanUtils.copyProperties(article, articleInfoDTO);
          return articleInfoDTO;
        })
        .collect(Collectors.toList());
    pageResult.setDataList(articleInfoDTOS);
    return pageResult;
  }
}
